/**
 * Copyright (C) 2013 The yydorid-framework project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.yangying.androidframework.util;

import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//import javax.xml.datatype.DatatypeConfigurationException;
//import javax.xml.datatype.XMLGregorianCalendar;

/**
 * StringUtil�����ࣺ�ַ�����ת������ش���
 * 
 * @author YANGYING
 * 
 * @date 2011-5-24
 */
public class StringUtil {

	public static final DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
	public static final DateFormat format2 = new SimpleDateFormat(
			"yyyy��MM��dd�� HHʱmm��ss��");

	/**
	 * SimpleDateFormat�����﷨��
	 * 
	 * G ����־�� 
	 * y �� 
	 * M �� 
	 * d �� 
	 * h ʱ ����������� (1~12) 
	 * H ʱ ��һ���� (0~23) 
	 * m �� 
	 * s �� 
	 * S ���� 
	 * E ���� 
	 * D һ���еĵڼ��� 
	 * F һ���еڼ������ڼ� 
	 * w һ���еڼ������� 
	 * W һ���еڼ������� 
	 * a ���� / ���� ��Ƿ� 
	 * k ʱ ��һ���� (1~24) 
	 * K ʱ ����������� (0~11) 
	 * z ʱ��
	 * 
	 * @param str
	 * @return
	 */
	public static Date getDate(DateFormat format,String datestr) {
		Date date = null;
		// StringתDate
		try {
			date = format.parse(datestr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	public static String getString(DateFormat format,Date date) {
		String str = null;
		// DateתString
		date = new Date();
		str = format.format(date);
		return str;
	}
//	public static XMLGregorianCalendar getXMLGregorianCalendar(String formate,String datestr) throws DatatypeConfigurationException
//	{
//        javax.xml.datatype.XMLGregorianCalendar cal = javax.xml.datatype.DatatypeFactory
//        	.newInstance().newXMLGregorianCalendar();
//		return cal;
//	}
//	public static void testCalendar3() throws Exception{
//        javax.xml.datatype.XMLGregorianCalendar cal = javax.xml.datatype.DatatypeFactory
//                .newInstance().newXMLGregorianCalendar();
//        cal.setMonth(12);
//        cal.setYear(2005);
//        
//        GregorianCalendar ca = cal.toGregorianCalendar();
//        String format = "MM/dd/yyyy HH:mm:ss";
//        SimpleDateFormat formatter = new SimpleDateFormat(format);
////        System.out.println(formatter.format(ca.getTime()));
//        
//    }
	public static String GBToUnicode(String   strIn)
	  {
	      byte[]   b;
	      String   strOut   =   null;
	      if(strIn   ==   null   ||   (strIn.trim()).equals( " "))
	          return   strIn;
	      try
	      {
	          b   =   strIn.getBytes( "ISO8859_1");
	          strOut   =   new   String(b, "GB2312");
	      }
	      catch(Exception   e)
	      {
//	          System.out.println( "GBToUnicode   exception   :   "   +   e.getMessage()   +   "\n ");
	      }
	      return   strOut;
	  } 
	public static String utf8Togb2312(String str){
	      StringBuffer sb = new StringBuffer();
	      for(int i=0; i<str.length(); i++) {
	          char c = str.charAt(i);
	          switch (c) {
	             case '+':
	                 sb.append(' ');
	             break;
	             case '%':
	                 try {
	                      sb.append((char)Integer.parseInt(
	                      str.substring(i+1,i+3),16));
	                 }
	                 catch (NumberFormatException e) {
	                     throw new IllegalArgumentException();
	                }
	                i += 2;
	                break;
	             default:
	                sb.append(c);
	                break;
	           }
	      }
	      // Undo conversion to external encoding
	      String result = sb.toString();
	      String res=null;
	      try{
	          byte[] inputBytes = result.getBytes("8859_1");
	          res= new String(inputBytes,"UTF-8");
	      }
	      catch(Exception e){}
	      return res;
	}
	   public static String gbToUtf8(String str) throws UnsupportedEncodingException {   
	        StringBuffer sb = new StringBuffer();   
	        for (int i = 0; i < str.length(); i++) {   
	            String s = str.substring(i, i + 1);   
	            if (s.charAt(0) > 0x80) {   
	                byte[] bytes = s.getBytes("Unicode");   
	                String binaryStr = "";   
	                for (int j = 2; j < bytes.length; j += 2) {   
	                    // the first byte   
	                    String hexStr = getHexString(bytes[j + 1]);   
	                    String binStr = getBinaryString(Integer.valueOf(hexStr, 16));   
	                    binaryStr += binStr;   
	                    // the second byte   
	                    hexStr = getHexString(bytes[j]);   
	                    binStr = getBinaryString(Integer.valueOf(hexStr, 16));   
	                    binaryStr += binStr;   
	                }   
	                // convert unicode to utf-8   
	                String s1 = "1110" + binaryStr.substring(0, 4);   
	                String s2 = "10" + binaryStr.substring(4, 10);   
	                String s3 = "10" + binaryStr.substring(10, 16);   
	                byte[] bs = new byte[3];   
	                bs[0] = Integer.valueOf(s1, 2).byteValue();   
	                bs[1] = Integer.valueOf(s2, 2).byteValue();   
	                bs[2] = Integer.valueOf(s3, 2).byteValue();   
	                String ss = new String(bs, "UTF-8");   
	                sb.append(ss);   
	            } else {   
	                sb.append(s);   
	            }   
	        }   
	        return sb.toString();   
	    } 
	   private static String getHexString(byte b) {   
	        String hexStr = Integer.toHexString(b);   
	        int m = hexStr.length();   
	        if (m < 2) {   
	            hexStr = "0" + hexStr;   
	        } else {   
	            hexStr = hexStr.substring(m - 2);   
	        }   
	        return hexStr;   
	    }   
	  
	    private static String getBinaryString(int i) {   
	        String binaryStr = Integer.toBinaryString(i);   
	        int length = binaryStr.length();   
	        for (int l = 0; l < 8 - length; l++) {   
	            binaryStr = "0" + binaryStr;   
	        }   
	        return binaryStr;   
	    } 
}
